#include "Socket.hpp"
#include <iostream>
#include <memory>
#include <sys/wait.h>

using namespace SocketModule;
using namespace LogModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket> &sock, InetAddr &client)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, ioservice_t service):
        _port(port),
        _listensocket(std::make_unique<TcpSocket>()),
        _service(service)
    {
        _listensocket->BuidTcpSocketMethod(_port);
    }

    void Start()
    {
        _is_running = true;
        while(_is_running)
        {
            InetAddr client;
            auto sock = _listensocket->Accept(&client); // 
            if(sock == nullptr)
            {
                continue;
            }
            LOG(LogLevel::DEBUG) << "accept success ...";

            pid_t id = fork();
            if(id < 0)
            {
                LOG(LogLevel::ERROR) << "fork error";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                _listensocket->Close();
                if(fork() > 0)
                    exit(0);
                _service(sock, client);
                exit(OK);
            }
            else
            {
                sock->Close();
                pid_t rid = ::waitpid(id, nullptr, 0);
                (void)rid;
            }
        }
        _is_running = false;
    }
    ~TcpServer() {}
private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensocket;
    bool _is_running = false;
    ioservice_t _service;
};
